package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.USER_SIGN_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号格式
        if (RegexUtils.isPhoneInvalid( phone)) {
            return Result.fail("手机号格式错误");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(6);

        //保存验证码到Redis
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY +  phone,
                code,
                RedisConstants.LOGIN_CODE_TTL,
                TimeUnit.MINUTES);
        //发送验证码 模拟
        log.info("发送验证码成功 {} :{}" , phone,code);
        return Result.ok();
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码
     * @return 登录结果
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //校验验证码
        String code = loginForm.getCode();
        String phone = loginForm.getPhone();
        //从redis获取验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        if(cacheCode == null){
            return Result.fail("验证码不存在");
        }
        log.info("验证码 {} :{}" , code,cacheCode);
        if(!cacheCode.equals( code)){
            return Result.fail("验证码错误");
        }
        //校验手机号
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号错误");
        }
        //根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //不存在 创建新用户 完善用户信息 保存用户信息到redis,mysql
        if(user == null){
            user=createUser(phone);
        }
        //存在 保存用户信息到redis
        //对用户信息进行脱敏
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //随机生成token 作为登录令牌
        String token = UUID.randomUUID().toString(true);
        log.info("token {}" , token);
        //将用户信息转为hash 存入redis
        //将用户信息转为hash 存入redis (确保所有值都是字符串)
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> {
                            return fieldValue.toString();
                        }));
        log.info("userMapString {}" , userMap.toString());
        //将用户信息转为hash 存入redis
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY + token,userMap);
        //设置用户信息有效期
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token,RedisConstants.LOGIN_USER_TTL,TimeUnit.SECONDS);
        //将token返回前端

        return Result.ok(token);
    }

    /**
     * 退出登录
     * @return
     */
    @Override
    public Result logout(HttpServletRequest  request) {

        //删除token
        String token = request.getHeader("authorization");
        stringRedisTemplate.delete(RedisConstants.LOGIN_USER_KEY + token);

        //删除用户
        UserHolder.removeUser();
        log.info("用户退出登录");

        return Result.ok();
    }

    /**
     * 签到功能
     * @return
     */
    @Override
    public Result sign() {
        //1. 获取当前的登陆用户
        UserDTO user = UserHolder.getUser();
        //2. 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        //3. 拼接业务的key
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String key =
                USER_SIGN_KEY +
                        user.getNickName() +
                        '_' + user.getId() +
                        '_' + keySuffix;
        //4. 获取签到日期
        int day = now.getDayOfMonth();
        //5. 写入Redis SETBIT key offset ture/false
        stringRedisTemplate.opsForValue().setBit(key, day-1, true);


        return Result.ok();
    }

    /**
     * 连续签到天数统计
     * @return
     */
    @Override
    public Result countSign() {
        //1. 获取当前登录用户
        UserDTO user = UserHolder.getUser();
        //2. 获取当前日期
        LocalDateTime now = LocalDateTime.now();
        int dayOfMonth = now.getDayOfMonth();
        //3.拼接业务的key
        String keySuffix = now.format(DateTimeFormatter.ofPattern("yyyy/MM"));
        String key = USER_SIGN_KEY +
                user.getNickName() +
                '_' + user.getId() +
                '_' + keySuffix;
        //4. 获取当前用户签到数据(返回十进制数)
        List<Long> signNum = stringRedisTemplate.opsForValue()
                .bitField(key,
                        BitFieldSubCommands
                                .create()
                                .get(BitFieldSubCommands
                                        .BitFieldType
                                        .unsigned(dayOfMonth))
                                .valueAt(0));
        if(signNum == null || signNum.isEmpty()){
            return Result.ok(0);
        }
        Long num = signNum.get(0);
        if(num == null || num == 0){
            return Result.ok(0);
        }

        //5. 循环右移 + 1与运算 得出连续签到天数
        int dayCount = 0;
        while(true) {
            if(((num & 1) == 0)){
                break;
            }else{
                dayCount ++;
            }
            num = num >> 1;
        }
        return Result.ok(dayCount);
    }


    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX +RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
